package com.lb.jwitter.action;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;

import com.lb.jwitter.service.ConditionReport;
import com.lb.jwitter.service.TblQLDTTXAHocKyTrongNam;
import com.lb.jwitter.service.TblQLDTTXAHocKyTrongNamService;
import com.lb.jwitter.service.TblQLDTTXAHocVien;
import com.lb.jwitter.service.TblQLDTTXAHocVienDangKyMonHoc;
import com.lb.jwitter.service.TblQLDTTXAHocVienDangKyMonHocService;
import com.lb.jwitter.service.TblQLDTTXAHocVienPhieuDangKyMonHoc;
import com.lb.jwitter.service.TblQLDTTXAHocVienPhieuDangKyMonHocService;
import com.lb.jwitter.service.TblQLDTTXAHocVienService;
import com.lb.jwitter.service.TblQLDTTXAMonHoc;
import com.lb.jwitter.service.TblQLDTTXAMonHocService;
import com.lb.jwitter.service.TblQuyenChiTietService;
import com.lb.jwitter.service.TblTaiKhoan;
import com.lb.jwitter.util.ApplicationContextProvider;
import com.lb.jwitter.util.ExcelToJSon;
import com.lb.jwitter.util.ExcelToJSon2;
import com.lb.jwitter.util.Message;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

@ContextConfiguration(locations = "classpath:beans.xml")
public class TblQLDTTXAHocVienPhieuDangKyMonHocUploadAction  extends ActionSupport implements Action, SessionAware {
	private TblTaiKhoan taiKhoanDangNhap;

	public TblTaiKhoan getTaiKhoanDangNhap() {
		return taiKhoanDangNhap;
	}

	public void setTaiKhoanDangNhap(TblTaiKhoan taiKhoanDangNhap) {
		this.taiKhoanDangNhap = taiKhoanDangNhap;
	}

	private Message msg;

	public Message getMsg() {
		return msg;
	}

	public void setMsg(Message msg) {
		this.msg = msg;
	}
	
	
	@Autowired // Injected by Spring 
    ApplicationContextProvider contextProvider; 
	private String destFile; 
	
	public String getDestFile() {
		return destFile;
	}
	public void setDestFile(String destFile) {
		this.destFile = destFile;
	}
	
	protected Map session;
	  
    public void setSession(final Map session) {
	   this.session = session;
    }
    
    TblQLDTTXAHocVienPhieuDangKyMonHocService tblQLDTTXAHocVienPhieuDangKyMonHocService;
    TblQLDTTXAHocVienService tblQLDTTXAHocVienService;
    TblQLDTTXAHocKyTrongNamService tblQLDTTXAHocKyTrongNamService;
    TblQLDTTXAHocVienDangKyMonHocService tblQLDTTXAHocVienDangKyMonHocService;
    TblQLDTTXAMonHocService tblQLDTTXAMonHocService;
	
    public String execute() throws Exception {

		try {

			//----------------------kiemtra quyen--------------------
			//Map session = ActionContext.getContext().getSession(); session chuyen tu FileUpload
			taiKhoanDangNhap = (TblTaiKhoan) session.get("taiKhoan");
			if (taiKhoanDangNhap == null)
				return "noprivilege";
			ApplicationContext context = ApplicationContextProvider.getApplicationContext(); 
			TblQuyenChiTietService tblQuyenChiTietService = (TblQuyenChiTietService) context.getBean("tbl_Quyen_ChiTietClient"); 
		    if(!tblQuyenChiTietService.checkRight(taiKhoanDangNhap.getMaNhomQuyen().getId(), "tbl_QLDTTXA_HocVien_PhieuDangKyMonHoc", "them")){ 
		        return "noprivilege"; 
		    }
		    tblQLDTTXAHocVienPhieuDangKyMonHocService = (TblQLDTTXAHocVienPhieuDangKyMonHocService) context.getBean("tbl_QLDTTXA_HocVien_PhieuDangKyMonHocClient");
		    tblQLDTTXAHocVienService = (TblQLDTTXAHocVienService) context.getBean("tbl_QLDTTXA_HocVienClient");
		    tblQLDTTXAHocKyTrongNamService = (TblQLDTTXAHocKyTrongNamService) context.getBean("tbl_QLDTTXA_HocKyTrongNamClient");
		    tblQLDTTXAHocVienDangKyMonHocService = (TblQLDTTXAHocVienDangKyMonHocService) context.getBean("tbl_QLDTTXA_HocVien_DangKyMonHocClient");
		    tblQLDTTXAMonHocService = (TblQLDTTXAMonHocService) context.getBean("tbl_QLDTTXA_MonHocClient");
		    
		    if(pageSize == 0){ 
	            pageSize = 20; 
	        } 
	        if(page == 0){ 
	            page =1; 
	        } 
		    
		    TblQLDTTXAHocKyTrongNam tblQLDTTXAHocKyTrongNam = tblQLDTTXAHocKyTrongNamService.gettblQLDTTXAHocKyTrongNam(new Long(hocKyId));
		    if(tblQLDTTXAHocKyTrongNam == null)
		    	return Action.ERROR;
		    
		    JSONArray jsons = new JSONArray();
			if (ExcelToJSon2.getExtension(destFile).equals("XLSX")) {
				System.out.println("EXCEL 2007: " + destFile);
				jsons = ExcelToJSon2.execute(destFile);				
			} else {
				System.out.println("EXCEL 2003: " + destFile);
				jsons = ExcelToJSon.execute(destFile);			
			}
			
			System.out.println("Jsons Size: " + jsons.size());
			
			TblQLDTTXAHocVienPhieuDangKyMonHoc pdkmh = null;
			List<ConditionReport> cons = new ArrayList<ConditionReport>();
			DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 
			
			List<TblQLDTTXAMonHoc> tblQLDTTXAMonHocs = tblQLDTTXAMonHocService.findAlltblQLDTTXAMonHoc(0, 0);
			Map monHocs = new HashMap<String, TblQLDTTXAMonHoc>();
			for(TblQLDTTXAMonHoc mh : tblQLDTTXAMonHocs){
				monHocs.put(mh.getMaMonHoc(), mh);
			}
			
			for(int i = 0 ; i < jsons.size(); i++){
				int linenum = i + 2;
				JSONObject obj = jsons.getJSONObject(i);
				
				try{
					String maHv = obj.getString("MAHV").trim();
					String monHoc = obj.containsKey("MH")? obj.getString("MH").trim(): "";
					String nhomDoi = obj.containsKey("NHOMDOI")? obj.getString("NHOMDOI").trim() : "";
					String huy = obj.containsKey("HUY")? obj.getString("HUY").trim(): "";
					String ngayCapNhat = obj.containsKey("NGAYCAPNHAT")? obj.getString("NGAYCAPNHAT").trim(): "";
					
					if(!huy.equalsIgnoreCase("")){
						continue;
					}
					
					if(pdkmh == null || !pdkmh.getHocVienId().getMSHV().equalsIgnoreCase(maHv)){
						TblQLDTTXAHocVien tblQLDTTXAHocVien = null;
						cons.clear();
						{
							
							ConditionReport con = new ConditionReport();
							con.setCol("MSHV");
							con.setValue1(maHv);
							con.setOperator("eq");
							cons.add(con);
						}
						List<TblQLDTTXAHocVien> hvs = tblQLDTTXAHocVienService.findtblQLDTTXAHocVienByCondition(cons, 0, 0);
						if(hvs == null || hvs.size() <= 0){
							System.out.println("Line " + linenum + " MSHV khong ton tai: " + maHv);
							continue;
						} else {
							tblQLDTTXAHocVien = hvs.get(0);
						}
						
						cons.clear();
				        {         	
				            ConditionReport con = new ConditionReport(); 
				            con.setCol("hocVienId.id");
				            con.setValue1(tblQLDTTXAHocVien.getId());
				            con.setOperator("eq");
				            cons.add(con);	
				        }
				        {         	
				            ConditionReport con = new ConditionReport(); 
				            con.setCol("hocKyId.id");
				            con.setValue1(tblQLDTTXAHocKyTrongNam.getId());
				            con.setOperator("eq");
				            cons.add(con);	
				        }
				        List<TblQLDTTXAHocVienPhieuDangKyMonHoc> pdks = tblQLDTTXAHocVienPhieuDangKyMonHocService.findtblQLDTTXAHocVienPhieuDangKyMonHocByCondition(cons, 0, 0);
				        if(pdks == null || pdks.size() <= 0){
				        	pdkmh = new TblQLDTTXAHocVienPhieuDangKyMonHoc();
				        	pdkmh.setCanBoNhanId(taiKhoanDangNhap.getCanBoId());
				        	pdkmh.setHocKyId(tblQLDTTXAHocKyTrongNam);
				        	pdkmh.setHocVienId(tblQLDTTXAHocVien);
				        	
				        	try {
				 	        Date dd = HSSFDateUtil.getJavaDate(Double.parseDouble(ngayCapNhat)); 
				 	        GregorianCalendar c = new GregorianCalendar(); 
				 	        c.setTime(dd);
				 	        XMLGregorianCalendar d = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); 
				        	pdkmh.setNgayNop(d);
				        	} catch(Exception ex){
								System.out.println("Line " + linenum + " ERROR date format");
								ex.printStackTrace();
							}
				        	
				        	Long pdkId = tblQLDTTXAHocVienPhieuDangKyMonHocService.createtblQLDTTXAHocVienPhieuDangKyMonHoc(pdkmh);
				        	pdkmh.setId(pdkId);
				        } else {
				        	pdkmh = pdks.get(0);
				        }
					}
					
					TblQLDTTXAHocVienDangKyMonHoc hvdkmh = new TblQLDTTXAHocVienDangKyMonHoc();
					TblQLDTTXAMonHoc mh = (TblQLDTTXAMonHoc) monHocs.get(monHoc);
					if(mh == null){
						System.out.println("Line " + linenum + " mon hoc khong ton tai: " + monHoc);
						continue;
					}
					hvdkmh.setDaXepLop(false);
					hvdkmh.setMonHocId(mh);
					hvdkmh.setPhieuDangKyId(pdkmh);
					tblQLDTTXAHocVienDangKyMonHocService.createtblQLDTTXAHocVienDangKyMonHoc(hvdkmh);
					
				}catch(Exception ex){
					System.out.println("Line " + linenum + " ERROR format file");
					ex.printStackTrace();
				}
			}
			
			cons.clear();
	        {         	
	            ConditionReport con = new ConditionReport(); 
	            con.setCol("hocKyId.id");
	            con.setValue1(tblQLDTTXAHocKyTrongNam.getId());
	            con.setOperator("eq");
	            cons.add(con);	
	        }
	        tblQLDTTXAHocVienPhieuDangKyMonHocs = tblQLDTTXAHocVienPhieuDangKyMonHocService.findtblQLDTTXAHocVienPhieuDangKyMonHocByCondition(cons, 0, 0);
	        pages = tblQLDTTXAHocVienPhieuDangKyMonHocService.counttblQLDTTXAHocVienPhieuDangKyMonHocByCondition(cons)/pageSize + 1;
	        dataString += "&hocKyId="+tblQLDTTXAHocKyTrongNam.getId() ; 
				
			return Action.SUCCESS;
		} catch (Exception e) {
			System.out.println("LOI UPLOAD Phieu DKMH Action");
			e.printStackTrace();
			return Action.ERROR;
		}

	}
    private int hocKyId;

	public int getHocKyId() {
		return hocKyId;
	}

	public void setHocKyId(int hocKyId) {
		this.hocKyId = hocKyId;
	}
	
	private List<TblQLDTTXAHocVienPhieuDangKyMonHoc> tblQLDTTXAHocVienPhieuDangKyMonHocs;

	public List<TblQLDTTXAHocVienPhieuDangKyMonHoc> getTblQLDTTXAHocVienPhieuDangKyMonHocs() {
		return tblQLDTTXAHocVienPhieuDangKyMonHocs;
	}

	public void setTblQLDTTXAHocVienPhieuDangKyMonHocs(
			List<TblQLDTTXAHocVienPhieuDangKyMonHoc> tblQLDTTXAHocVienPhieuDangKyMonHocs) {
		this.tblQLDTTXAHocVienPhieuDangKyMonHocs = tblQLDTTXAHocVienPhieuDangKyMonHocs;
	}
	
	private int pageSize; 
    public int getPageSize() {
       return pageSize;
 }

    public void setPageSize(int pageSize) { this.pageSize = pageSize; }

    private int page; 
    public int getPage() { return page; }

    public void setPage(int page) { this.page = page; }

    private int pages; 
    public int getPages() { return pages; }

    public void setPages(int pages) { this.pages = pages; }

    private String dataString; 
    public String getDataString() { return dataString; }
}
